﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ITAP.ShprossesBuilder.Modelling.Components.Constraints
{
    [Serializable]
    public class ConnectedComponentsDisconnectByUniqueIdConstraint : IConstraint
    {
        public ConnectedComponentsDisconnectByUniqueIdConstraint()
        {
        }

        #region IConstraint Members

        public bool Check(IComponent component)
        {
            if (!component.UniqueIdsEnabled)
                return true;

            foreach (IComponent connectedComponent in component.ConnectedComponents)
            {
                if (connectedComponent.UniqueId != -1 && !component.AcceptedUniqueIdsToConnect.Contains(connectedComponent.UniqueId))
                    return false;
            }
            return true;
        }

        public void Fix(IComponent component)
        {
            if (!this.enabled)
                return;

            if (!component.UniqueIdsEnabled || component.AcceptedUniqueIdsToConnect.Count == 0)
                return;

            List<IComponent> componentsToDisconnect = new List<IComponent>();
            foreach (IComponent connectedComponent in component.ConnectedComponents)
            {
                
                if (connectedComponent.UniqueId != -1 && !component.AcceptedUniqueIdsToConnect.Contains(connectedComponent.UniqueId))
                    componentsToDisconnect.Add(connectedComponent);
            }
            foreach (IComponent componentToDisconnect in componentsToDisconnect)
            {
                if(!component.RemoveInnerComponent(componentToDisconnect))
                    ConnectionProvider.Disconnect(component, componentToDisconnect);
            }

        }
        private bool enabled = true;
        public bool Enabled
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
            }
        }

        public ConstraintAction Action
        {
            get { return ConstraintAction.Disconnect; }
        }

        #endregion

        #region ICloneable Members

        public object Clone()
        {
            ConnectedComponentsDisconnectByUniqueIdConstraint clone = new ConnectedComponentsDisconnectByUniqueIdConstraint();
            clone.enabled = this.enabled;            
            return clone;
        }

        #endregion
    }
}
